$(function () {
    class details {
        constructor() {
            this.usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
            if (this.usermsg !== null) {
                this.writeUserMsg();
            }
            this.cart_data = this.getCartData();
            this.id = location.hash.split("=")[1];
            this.data = null;
            this.shopNum = 1;
            this.bindEvent();
            this.init()
            new lazyLoad(".detimg img")
            this.renderShopNum()

        }
        init() {
            let options = {
                url: "http://localhost:3000/static/data/dataAll.json"
            }
            axios(options)
                .then((res) => {
                    this.data = res.data
                    this.render(res.data);
                });
        }
        writeUserMsg() {
            $(".right-login1").css({
                display: "none"
            })
            $(".right-login2").css({
                display: "inline-block"
            })
            $("#login-n").html(this.usermsg.username)
        }
        bindEvent() {
            // 修改加入购物车数量
            // 减
            $("#quantity2").on("click", ".btna1", (e) => {
                if (this.shopNum <= 1) {
                    this.shopNum = 1;
                } else {
                    this.shopNum--
                }
                this.renderShopNum()
            })
            // 加
            $("#quantity2").on("click", ".btna2", (e) => {
                if (this.shopNum >= 20) {
                    this.shopNum = 20;
                } else {
                    this.shopNum++
                }
                this.renderShopNum()
            })

            // 立即购买
            $("#productaction").on("click", ".gobuythis", (e) => {
                let id = $(e.target).attr("data-id")
                $(".buyShop").css({
                    display: "block"
                })
                let res = this.search(id)
                this.renserbuy(res)
            })
            $("#buyShop").on("click", ".buyshoperr", (e) => {
                $(".buyShop").css({
                    display: "none"
                })
            })
            $("#buyShop").on("click", ".buyimg1", (e) => {
                $(".buyShop").css({
                    display: "none"
                })
            })

            //  添加购物车
            $("#productaction").on("click", ".addshopcar", (e) => {
                let id = $(e.target).attr("data-id")
                let res = this.search(id)
                if (res) {
                    this.addCart(id, res);
                    $(".shopcaert").css({
                        display: "block"
                    })
                } else {
                    $(".shopcaerterr").css({
                        display: "block"
                    })
                }
            })

            // 加入购物车成功的弹框
            $("#shopcart").on("click", ".sucimg1", (e) => {
                $(".shopcaert").css({
                    display: "none"
                })
            })
            $("#shopcart").on("click", ".gobuyshop", (e) => {
                $(".shopcaert").css({
                    display: "none"
                })
            })
            $("#shopcart").on("click", ".goshopcart", (e) => {
                $(".shopcaert").css({
                    display: "none"
                })
                location.href = "./shopCar.html";
            })

            // 加入购物车失败的弹框
            $("#shopcarterr").on("click", ".errimg1", (e) => {
                $(".shopcaerterr").css({
                    display: "none"
                })
            })
            $("#shopcarterr").on("click", ".errbtn", (e) => {
                $(".shopcaerterr").css({
                    display: "none"
                })
            })

            // 固定栏
            $(window).scroll((e) => {
                let scrolltop = $(document).scrollTop()
                if (scrolltop > 700) {
                    $("#fixedfield").css({
                        display: "block"
                    })
                } else {
                    $("#fixedfield").css({
                        display: "none"
                    })
                }
            }) 
            // 返回顶部
            $("#fixedfield").on("click", ".grouptop", (e) => {
                $("body,html").animate(
                    {
                        scrollTop: 0
                    },
                    800
                );
            })

            $.onclick = () => {
                g.remove(2);
            }
        }
        renderShopNum() {
            var html = "";
            html += ` <label class="item-label" for="for_quantity_input">数量：</label>
            <span class="item-content">
                <span class="p-quantity" id="quantity">
                    <div class="btn_a1 btna1">-</div>
                    <input type="text" value="${this.shopNum}" class="inp1" id="inpvalue">
                    <div class="btn_a2 btna2">+</div>
                    <input type="hidden" name="stock" value="1" class="inp2">
                </span>
                <span class="p-store"></span>
            </span>`
            $("#quantity2").html(html)
        }

        renserbuy(res) {
            var buyprice = this.shopNum * res.price
            var html = "";
            html += `共选购<span>${this.shopNum}</span>件商品，合计<span>${buyprice}</span>元，是否继续进行支付`
            $("#buygop").html(html)
        }

        render(res) {
            var $goodsdetail = res.data.filter(item => {
                if (Number(item.product_id) === Number(this.id)) {
                    return item
                }
            })
            var $title = $goodsdetail.map(item =>
                ` <h1>${item.product_name}</h1>
                <h3>${item.subtitle}</h3>
                <a>
                    <p>
                        【9/1换新季 限时赠价值368元TUF双肩包+意外险】全新锐龙R7-5800H处理器，搭配GeForce RTX
                        3060系显卡，订单五分钟之内未支付将会被关闭。每个id限购一台 </p>
                </a> `
            )
            $("#product-titles").html($title)

            var $buy = $goodsdetail.map(item =>
                ` <div 
                class="bton1"><span><span class="gobuythis" data-id="${item.product_id}">立即购买</span></span></div>
            <div data-id="${item.product_id}"
                class="bton2"><span><span class="addshopcar" data-id="${item.product_id}">加入购物车</span></span></div> `
            )
            $("#productaction").html($buy)

            var $price = $goodsdetail.map(item =>
                `<ul>
                <li>
                    <span class="label">限时钜惠</span>
    
                    <span class="detail">
                        <b class="price">
                            <ins class="action-price">${item.price}</ins>
                            <ins class="action-oldprice">${item.market_price}</ins>
                        </b>
                        <span class="activity-rule">活动规则</span>
                    </span>
                </li>
            </ul>`
            )
            $("#product-concerns").html($price)
        }

        // 加入购物车
        search(id) {
            let res = null;
            let good_data = this.data
            good_data.data.some(item => {
                if (Number(id) === Number(item.product_id)) {
                    res = item;
                    return true;
                }
            })
            return res;
        }
        getCartData() {
            try {
                let data = JSON.parse(localStorage.getItem("cart"))
                if (data === null) {
                    return {}
                }
                return data;
            } catch (e) {
                return {};
            }
        }
        addCart(id, data) {
            // 判断当前的id是否存在于购物车列表之中
            if (id in this.cart_data) {
                // 如果购物车存在商品，将购物车数量+将要加入的商品数量; 
                this.cart_data[id].count += this.shopNum;
            } else {
                // 如果不存在就放入一个拥有多个商品数量的初始数据; 
                data.count = this.shopNum;
                this.cart_data[id] = data;
            }
            this.save();
        }
        save() {
            localStorage.setItem("cart", JSON.stringify(this.cart_data));
        }

    }
    new details;
})